<script setup>
import { computed, onMounted, reactive, ref, watchEffect } from 'vue';
import data from "@/untils/address/states.json"
const formLabelWidth = '100px'
import { ElMessage } from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { Decrypt, Encrypt } from '../../untils/passjs/security';
import EditCdkeyPanel from './EditCdkeyPanel.vue';
import { getcdkeypanelapi, fronttestapi, createdurationapi, createtestapi, createforeverapi, sendtextmessageapi } from '../../api/api';
let formRef = ref(null)
let props = defineProps({
    PaneldialogFormVisible: Boolean,
    equipmentIdvalue: Number
})
watchEffect(() => {
    if (props.PaneldialogFormVisible) {
        getCdkeyPanel()
    }
})
let CdkeyPanelData = ref({})
let activationId = ref(null)
async function getCdkeyPanel() {
    try {
        let res = await getcdkeypanelapi(props.equipmentIdvalue)
        console.log(res);
        if (res.code == 200) {
            //  if(res.data == null){
            //     console.log("wu "); 
            //      ElMessage.warning('This device currently does not have an activation code. Please click to generate it')
            // }
            console.log(res.data.activationId);

            activationId.value = res.data.activationId
            // swichtime(res.data.timeType)
            switchactivationDayfun(res.data.activationDay)
            CdkeyPanelData.value = res.data

        }
    } catch (error) {
        console.log(error);

    }
}
onMounted(() => {
})

let emits = defineEmits(["closePanel"])
function colseclose(formRef) {
    emits("closePanel")
    CdkeyPanelData.value = {}
    inptextmodel.value = ''
    selectmodel.value = 1
    switchactivationDay.value = ''
    activationId.value = null
    // closedialog(formRef)
    // if(props.dialogFormVisible){
    // roleOptions.value =[]
    // }
}
let selectmodel = ref(1)
let inptextmodel = ref('')
// let remaintimestr = ref('')
// let swichtime = (timeType) => {
//     switch (timeType) {
//         case 1:
//             remaintimestr.value = 'second'
//             break;
//         case 2:
//             remaintimestr.value = 'minute'
//             break;
//         case 3:
//             remaintimestr.value = 'hour'
//             break;
//         case 4:
//             remaintimestr.value = 'day'
//             break;
//     }
// }

let icondialogFormVisible = ref(false)
function closeiconfun() {
    icondialogFormVisible.value = false
}
let dialogVisible = ref(false)
let dialogVisiblesure = ref(false)
async function testcreatefun() {
    console.log(typeof inptextmodel.value);

    if (selectmodel.value == 1) {
        if (inptextmodel.value == '') {
            ElMessage.warning("Please enter the number of days to be generated")
            return;
        }
    }
    let res = await fronttestapi(props.equipmentIdvalue)
    console.log(res);
    if (res.data) {
        dialogVisible.value = true
    } else {
        dialogVisiblesure.value = true
    }

}
async function yesdel() {
    console.log(props.equipmentIdvalue);
    console.log(selectmodel.value);
    console.log(inptextmodel.value);
    let requestData = {}
    if (selectmodel.value == 1) {
        requestData = {
            equipmentId: props.equipmentIdvalue,
            activationDay: +inptextmodel.value
        }
        try {
            let res = await createdurationapi(requestData);
            console.log(res);
            if (res.code == 200) {
                dialogVisible.value = false;
                dialogVisiblesure.value = false;
                inptextmodel.value = ''
                getCdkeyPanel()
            }
        } catch (error) {
            console.log(error);

        }
    } else if (selectmodel.value == 2) {
        requestData = {
            equipmentId: props.equipmentIdvalue
        }
        try {
            let res = await createtestapi(requestData);
            console.log(res);
            if (res.code == 200) {
                dialogVisible.value = false;
                dialogVisiblesure.value = false;
                getCdkeyPanel()
            }
        } catch (error) {
            console.log(error);

        }
    } else if (selectmodel.value == 3) {
        requestData = {
            equipmentId: props.equipmentIdvalue
        }
        try {
            let res = await createforeverapi(requestData);
            console.log(res);
            if (res.code == 200) {
                dialogVisible.value = false;
                dialogVisiblesure.value = false;
                getCdkeyPanel()
            }
        } catch (error) {
            console.log(error);

        }
    }
    selectmodel.value = 1
    switchactivationDay.value = ''
    activationId.value = null

}
let switchactivationDay = ref('')
let switchactivationDayfun = (activationDay) => {
    if (activationDay == 0) {
        switchactivationDay.value = 'Test'
    } else if (activationDay == -1) {
        switchactivationDay.value = 'Permanent'
    } else if (activationDay == -2) {
        switchactivationDay.value = 'reset'
    } else {
        switchactivationDay.value = `Effective\n${activationDay}day`
    }
}
function handleNumberInput(value) {
    if (typeof value === 'string') {
        const num = Number(value)
        if (isNaN(num)) {
            inptextmodel.value = ''
        } else if (num < 1) {
            inptextmodel.value = ''
            ElMessage.warning("The minimum number of days is 1")
        } else if (num > 180) {
            inptextmodel.value = ''
            ElMessage.warning("The maximum number of days is 180")
        } else {
            inptextmodel.value = num
        }
    } else if (typeof value === 'number') {
        if (value < 1) {
            inptextmodel.value = ''
        }
    }
}
const isSmsButtonDisabled = ref(false);
const smsButtonText = ref('Send SMS');
const smsCountdown = ref(180);
const smsTimer = ref(null);
async function sendtextmessage() {
    console.log('发送短信');
    // 禁用按钮
    isSmsButtonDisabled.value = true;
    smsCountdown.value = 180;
    smsButtonText.value = `${smsCountdown.value}s`;

    var el = document.querySelector(".sendsms")
    console.log(el);
    el.style.backgroundColor = '#d2e3ca'
    el.style.border = '0'
    try {
        let res = await sendtextmessageapi({ activationId: activationId.value })
        // let res = {
        //     code: 500,
        //     data: false,
        //     msg: "dsafsa"
        // }
        console.log(res);
        if (res.code == 200) {
            smsTimer.value = setInterval(() => {
                smsCountdown.value--;
                if (smsCountdown.value > 0) {
                    smsButtonText.value = `${smsCountdown.value}s`;
                } else {
                    clearInterval(smsTimer.value);
                    smsButtonText.value = 'Send SMS';
                    isSmsButtonDisabled.value = false;
                    smsTimer.value = null;
                    el.style.backgroundColor = '#67c23a'
                    el.style.border = '#67c23a'
                }
            }, 1000);
            if (res.data) {
                ElMessage.success(res.msg)
                smsButtonText.value = 'Send SMS';
            } else {
                smsButtonText.value = 'Send SMS';
                clearInterval(smsTimer.value);
                isSmsButtonDisabled.value = false;
                ElMessage.warning('SMS sending failed, please contact the administrator to check')
                el.style.backgroundColor = '#67c23a'
                el.style.border = '#67c23a'
            }
        } else {
            ElMessage.error(res.msg)
            clearInterval(smsTimer.value);
            smsButtonText.value = 'Send SMS';
            isSmsButtonDisabled.value = false;
            el.style.backgroundColor = '#67c23a'
            el.style.border = '#67c23a'
        }
    } catch (error) {
        // ElMessage.error(error)
        console.log(error);

    }

}
const hasPermission = (permission) => {
    const permissions = JSON.parse(localStorage.getItem("userdetail"))?.auths || [];
    if (permissions[0] === '*:*:*') {
        return true; // 如果有 *:*:* 权限，直接返回 true
    }
    return permissions.includes(permission);
};
</script>
<template>
    <div class="editclass">
        <el-dialog :model-value="PaneldialogFormVisible" style="padding: 40px;width: 800px;"
            title="Invitation Code Panel" @close="colseclose">
            <div class="top">
                <div class="eqcode">
                    equipment code:{{ CdkeyPanelData.equipmentNumber }}
                </div>
                <div style="display: flex;align-items: center;">
                    <div class="operatorclass">
                        operator:{{ CdkeyPanelData.optUsername }}
                    </div>
                    <el-icon size="30" @click="icondialogFormVisible = true" style="cursor: pointer;"
                        v-if="hasPermission('activation:equipment:query')">
                        <Document />
                    </el-icon>
                </div>
            </div>
            <div class="centerclass">
                <span>{{ CdkeyPanelData.activationCode?.replace(/(\d{3})(?=\d)/g, '$1 ') }}</span>
                <div class="remaintime">
                    {{ switchactivationDay }}
                </div>
            </div>
            <div class="createtimevlass">
                generation time: <span>{{ CdkeyPanelData.generationTime }}</span>
            </div>
            <!-- <div class="endtimmeclass" v-if="CdkeyPanelData.activationDay !== -1 && CdkeyPanelData.activationDay !== -2">
                expiration time: <span>{{ CdkeyPanelData.expirationTime }}</span>
            </div> -->
            <div class="lineclass"></div>
            <div class="bottomclass">
                <el-select style="width: 200px" placeholder="Select generate mode" v-model="selectmodel">
                    <el-option label="Custom days" :value="1" v-if="hasPermission('activation:generate:duration')" />
                    <el-option label="Test activation code" :value="2"
                        v-if="hasPermission('activation:generate:test')" />
                    <el-option label="Permanent activation code" :value="3"
                        v-if="hasPermission('activation:generate:perpetual')" />
                </el-select>
                <el-input v-model="inptextmodel" :min="1" :max="180" maxlength="180"
                    placeholder="Please input your generate mode" show-word-limit type="number"
                    style="width: 250px;margin-left: 20px;" :disabled='selectmodel == 1 ? false : true'
                    @input="handleNumberInput" />
                <div class="rightbox"></div>
                <el-button style="margin-left: 20px;" type="primary" @click="testcreatefun">generate</el-button>

            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="colseclose">cancel</el-button>
                    <el-button style="margin: 0px 20px 0;" class="sendsms" :disabled="isSmsButtonDisabled"
                        type="success" @click="sendtextmessage" v-if="hasPermission('activation:sms:send')">{{
                            smsButtonText }}</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogVisible" width="500">
            <span>There is already an activation code in use {{ CdkeyPanelData.activationCode?.replace(/(\d{3})(?=\d)/g,
                '$1 ')
                }} ,Are you sure you want to regenerate?</span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">cancel</el-button>
                    <el-button type="primary" @click="yesdel()">
                        sure
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogVisiblesure" width="500">
            <span>Are you sure you want to generate an activation code?</span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisiblesure = false">cancel</el-button>
                    <el-button type="primary" @click="yesdel()">
                        sure
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <EditCdkeyPanel :icondialogFormVisible="icondialogFormVisible" @closeicon="closeiconfun"></EditCdkeyPanel>
    </div>
</template>
<style lang="scss" scoped>
.two-column-form .form-row {
    display: flex;
    justify-content: center;
    align-items: center;
}

.two-column-form .el-form-item {
    width: 45%;
}

.address-container {
    display: flex;
    align-items: center;
}

/* 调整表单标签宽度 */
.two-column-form :deep(.el-form-item__label) {
    width: 80px;
    text-align: right;
    padding-right: 12px;
}

/* 响应式设计 - 小屏幕时变为单列 */
@media (max-width: 768px) {
    .two-column-form .form-row {
        flex-direction: column;


        .el-form-item {
            width: 100%;
        }
    }

    .address-container {
        flex-direction: column;
        align-items: flex-start;

        .el-select {
            width: 100% !important;
            margin-right: 0 !important;
            margin-bottom: 10px;
        }
    }
}

.top {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .eqcode {
        // width: 250px;
        font-size: 20px;
        text-align: center;
    }

    .operatorclass {
        margin-right: 30px;
    }

}

.centerclass {
    display: flex;
    align-items: center;
    justify-content: space-between;

    span {
        font-size: 55px;
        margin: 20px;
        color: cadetblue;
        font-weight: bold;
    }

    .remaintime {
        font-size: 25px;
        margin-right: 40px;
        white-space: pre-line;
        text-align: center;
    }
}

.createtimevlass,
.endtimmeclass {
    font-size: 20px;
    margin: 20px 0;

    span {
        color: burlywood;
    }
}

.bottomclass {
    display: flex;
    margin-bottom: 20px;
}

.lineclass {
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    margin: 20px 0;
}
</style>